# -*- coding: utf-8 -*-

'''
Copyright (C) 2011 Daniele Simonetti

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'''

import sys, locale, string, socket, time, re, os
### PySide ###
import PySide
### UI ###
from showinfo_ui import *
### CONTENT PROVIDERS ###
import providers

from myepes_rc import *

### DATE TIME ###
from datetime import timedelta, datetime, date

### ITEM DELEGATE ###
from itemdelegates.epitemdelegate import *

EP_STATUS_AIRED   = 0x01
EP_STATUS_UNAIRED = 0x02

########## SHOW INFO CLASS ############
class ShowInfo(QtGui.QWidget, Ui_ShowInfo):
  
  # Define signals
  needShowEpList = QtCore.Signal(str)
  needShowInfo = QtCore.Signal(str)

  def __init__(self, wlist, parent=None):
    super(ShowInfo, self).__init__(parent)
    self.setupUi(self)
    self.model = EpisodesModel(self)
    self.wlist = wlist
    self.cbShows.setModel(self.wlist.model)
    self.cbShows.setModelColumn(1)
    self.lvEps.setModel(self.model)
    self.lvEps.setItemDelegate( EpItemDelegate(self) )    
    
    self.setStyleSheet('''
QComboBox::drop-down { 
	margin: 7px;
    subcontrol-origin: margin;
}''')        

    # BIG FONT
    big_font = QtGui.QFont(self.font().family(), 16)
    self.cbShows.setFont(big_font)
    
    # MEDIUM FONT
    med_font = QtGui.QFont(self.font().family(), 11)
    self.lvEps.setFont(med_font)   
    
    # LITTLE FONT
    lil_font = QtGui.QFont(self.font().family(), 7)
    
    # CALC FONT METRICS
    metrics_1 = QtGui.QFontMetrics(med_font)
    metrics_2 = QtGui.QFontMetrics(lil_font)
    self.model.item_size = QtCore.QSize(metrics_1.height()+metrics_2.height()+6, metrics_1.height()+metrics_2.height()+6)
    print self.model.item_size

  def event(self, e):
    if e.type() == providers.showsEventType:
      self.foundShow(e.shows[0])
      return True
    elif e.type() == providers.epsEventType:
      self.foundEpisodes(e.source['showid'], e.eps)
      return True
    return super(ShowInfo, self).event(e)

  def loadShow(self, index):
    showid = self.cbShows.itemData(index)
    self.needShowEpList.emit(showid)
    self.needShowInfo.emit(showid)
    self.lbInfo.setText('<h1>Loading...</h1>')

  def foundShow(self, show):
    info = '''
    <a href='%s' alt='Link to TvRage'><img src='%s' style='float:left'/></a>
    <br/>
    <p>
    <table border="0" cellpadding="4">
    <tr><td><b>Started</b></td><td>%s</td></tr>
    <tr><td><b>Ended</b></td><td>%s</td></tr>
    <tr><td><b>Country</b></td><td>%s</td></tr>
    <tr><td><b>N. of seasons</b></td><td>%s</td></tr>
    <tr><td><b>Runtime</b></td><td>%s minutes</td></tr>
    <tr><td><b>Status</b></td><td>%s</td></tr>
    </table>    
    </p>
    ''' % (show.link, show.local_image, show.started, show.ended or 'N/A', show.country, show.seasons, show.runtime, show.status)
    self.lbInfo.setText(info)

  def foundEpisodes(self, showid, eps):
    self.model.update(showid, eps)


### EPISODES MODEL ###
class EpisodesModel(QtCore.QAbstractTableModel):
  def __init__(self, parent=None):
    super(EpisodesModel, self).__init__(parent)        
    self.wp = parent
    self.items = []
    self.showid = 0
            
    self.status_colors = { EP_STATUS_UNAIRED: QtGui.QBrush(QtGui.QColor(0xff, 0xe3, 0x59)),
                           EP_STATUS_AIRED: QtGui.QBrush(QtGui.QColor(0xe0, 0xe0, 0xe0)) }
                           
    self.status_colors_alt = { EP_STATUS_UNAIRED: QtGui.QBrush(
                               self.status_colors[EP_STATUS_UNAIRED].color().lighter()),
                               EP_STATUS_AIRED: QtGui.QBrush(
                               self.status_colors[EP_STATUS_AIRED].color().lighter()) }
                           
    self.text_color = QtGui.QBrush(QtGui.QColor(0x15, 0x15, 0x15))
    self.item_size = QtCore.QSize(36,36)    
  
  def rowCount(self, parent = QtCore.QModelIndex()):
    return len(self.items)
  
  def columnCount(self, parent = QtCore.QModelIndex()):
    return 1   
    
  def data(self, index, role):
    item = self.items[index.row()]
    today = date.today()    
    try:
        airdate = datetime.strptime(item.airdate, '%Y-%m-%d').date()
    except:
        airdate = date.min
        
    if role == QtCore.Qt.DisplayRole:
        return unicode(item)
    elif role == QtCore.Qt.BackgroundRole:           
        if airdate <= today:
            if index.row() % 2 != 0:
                return self.status_colors_alt[ EP_STATUS_AIRED ]
            return self.status_colors[ EP_STATUS_AIRED ]
        else:
            if index.row() % 2 != 0:
                return self.status_colors_alt[ EP_STATUS_UNAIRED ]        
            return self.status_colors[ EP_STATUS_UNAIRED ]
    elif role == QtCore.Qt.UserRole:
        return item
    elif role == QtCore.Qt.ForegroundRole:
        return self.text_color    
    elif role == QtCore.Qt.SizeHintRole:
        return self.item_size
     
  def flags(self, index):
    if not index.isValid():
        return QtCore.Qt.NoItemFlags
    flags = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable
    return flags    
    
  def update(self, id, items):
    #print 'update eps for show %s, n. %d' % (id, len(items))
    self.showid = id
    self.items = items
    self.emit(QtCore.SIGNAL('dataChanged(QModelIndex, QModelIndex)'), 
    self.index(0,0), self.index(len(self.items)-1,0))    
